﻿var TMOB_URL = "https://www.t-mobile.co.uk:443/service/your-account/login/"
var TMOB_NUM = "https://www.t-mobile.co.uk/service/your-account/private/home/"

var DOCKED_HEIGHT = 116;
var UNDOCKED_HEIGHT = 164;

//options keys
var USERNAME_OPTIONS_KEY = 'username';
var PASSWORD_OPTIONS_KEY= 'password';
var NUMBER_OPTIONS_KEY = 'number';

// Whitespace after Flext allowance
var WHITESPACE = 127;
var UNBILLED_WHITESPACE = 12;

// Refresh interval of gadget
var LOGIN_INTERVAL = 7200 * 1000;

var logina = 0;
var calc = 0;

//Drawing variables
var isDocked = false;
var isMinimized = false;

var http = null;
debug.info("Start");
function onOpen() {
	debug.info('open');

// Assume gadget is docked
  isDocked = true;

// Handle notifications sent when gadget is docked or undocked.
  pluginHelper.onDisplayTargetChange = onDisplayTargetChange;

  // Handle notifications sent when gadget is minimized. 
  view.onminimize = onMinimize;
  // Handle notifications sent when gadget is restored (maximized)
  view.onrestore = onRestore; 
	// Refresh the gadget to correct size
	draw();
// Check if options are set. If not then show login screen
  if(!options.getValue('username') || !options.getValue('password') || !options.getValue('number') || logina == 1) {
		divLoginDetailsError.visible = "false";
		divUserInfo.visible = "true";
	}
  else { 
		divLoginDetailsError.visible = "false";
		divUserInfo.visible = "false";
		login() ;
	}
}

//on login click set functions and move to login proedure
function onClickLogin() {
	debug.info('login click');
  if(!editUser.value || !editPass.value || !editPhone.value) {
    alert('Please fill in all details');
		return;
 	}
  
	options.putValue(USERNAME_OPTIONS_KEY,editUser.value);
  options.putValue(PASSWORD_OPTIONS_KEY,editPass.value);
  options.putValue(NUMBER_OPTIONS_KEY,editPhone.value);
	logina=0;
  login();
}

function onOptionChanged() {
  login();
}

function checklogin(){
// Check if login details are saved. Show div if not
	debug.info('check login');
	if(!options.getValue(USERNAME_OPTIONS_KEY) || !options.getValue(PASSWORD_OPTIONS_KEY) || !options.getValue(NUMBER_OPTIONS_KEY)) {
		onOpen;
		return;
	} else { divUserInfo.visible = 'False'; }

  http = new XMLHttpRequest();
  http.onreadystatechange = checkloginrespons;
  http.open("GET",TMOB_NUM,false);
 	http.send();
}

//parse page for billing details
function checkpage() {
	debug.info('check page');
	http = new XMLHttpRequest();
  var number = options.getValue(NUMBER_OPTIONS_KEY);

  //load correct billing page
	var params = "ctn=" + number;

	http.onreadystatechange = checkpageresponse;

  http.open("POST",TMOB_NUM,false);
  http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	try{
		http.send(params);
	} catch (e) {
		alert("Connection error 3");
	}
}

function checkpageresponse() {
if (http.readyState == 4) {
      var doc = new DOMDocument();
      doc.resolveExternals = false;
      doc.validateOnParse = false;
      doc.setProperty('ProhibitDTD', false);
	
      doc.loadXML(http.responseText);

			debug.info('test');
			var bufa = http.responseText.indexOf('Flext Allowance') + WHITESPACE;
			var bufb = http.responseText.indexOf('.', bufa) + 3;
			var remaining = http.responseText.substring(bufa,bufb);
			var unbilleda = http.responseText.indexOf('highlight') + UNBILLED_WHITESPACE;
			var unbilledb = http.responseText.indexOf('.', unbilleda) + 3;
			var unbilled = http.responseText.substring(unbilleda,unbilledb);
			debug.trace(unbilled);
			calc = remaining.substring(1,bufb);
			debug.trace(calc);
      labelMinutes.innerText = calc * (1/0.2);
      labelSMS.innerText = calc * (1/0.1);
      labelAmount.innerText = remaining;
			labelAmountUnbilled.innerText = '£' + unbilled;
			var timer = setInterval(login,LOGIN_INTERVAL);
	}
  return;
}

function login() {
  divConnectionError.visible = "false";
	debug.info('login');
  var user = options.getValue(USERNAME_OPTIONS_KEY);
  var pass = options.getValue(PASSWORD_OPTIONS_KEY);
  var http = new XMLHttpRequest();
	var params = "submit=Login&username=" + user + "&password=" + pass;
	http.onreadystatechange = onReadyStateChange;

  try{ 
		http.open("POST",TMOB_URL,true);
	} catch (e) {
		alert("Connection failure");
	}
  http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
  	
   function onReadyStateChange() {
		if(http.readyState != 4)
			return;
		
		if(http.status != 200 || !isOnline()) {
			divConnectionError.visible = "true";
			debug.info("Connection down");
	    waitForOnline(login);
			return;
		}
	
		var doc = new DOMDocument();
    doc.resolveExternals = false;
    doc.validateOnParse = false;
    doc.setProperty('ProhibitDTD', false);
	  doc.loadXML(http.responseText);
		debug.info('pre login check');
		if(http.responseText.match("warning")){
			divLoginDetailsError.visible = "true";
			alert("Login Details Incorrect");
		//	options.putValue("password",null);
			logina = 1;
    	return;
		} else {
			debug.info('correct login');
			logina = 0;
			divUserInfo.visible = false;
			var timer = setInterval(checkpage(),100);
			return;
		}
	} 

  try{
		http.send(params);
	} catch (e) {
		alert("Connection Failed");
	}
}

function isOnline(){
  return framework.system.network.online;
}

function waitForOnline(callback) {
  var RETRY_DELAY_MS = 60 * 1000;

  if (isOnline()) {
    // We're back, call the callback.
    callback();
  } else {
    // Try again later.
    view.setTimeout(function() { waitForOnline(callback); }, RETRY_DELAY_MS);
  }
}

function onDisplayTargetChange(displayTarget){
 if (displayTarget == gddTargetSidebar) {
    debug.trace('Display target changed to docked');
    isDocked = true;
    draw();
  } else if (displayTarget == gddTargetFloatingView) {
    debug.trace('Display target changed to undocked');
    isDocked = false;
    draw();
  }
}

function onMinimize(){
  debug.trace('Minimized');
  isMinimized = true;
  draw();
}

function onRestore(){
  debug.trace('Restored');
  isMinimized = false;
  draw();
}

// Draw the gadget.
function draw() {
  if (isMinimized) {
    // The gadget is minimized.
    // Write status to the caption.
    var caption = '';
    caption += '£' + calc; 
    // Set the caption (title bar).
    view.caption = caption;

    // Nothing else to do, return.
    return;
  } else {
    // The gadget is not minimized..
    // Set to normal caption.
    view.caption = strings.GADGET_NAME;
  }
  
  // Special handling for when the gadget is docked or undocked.
  if (isDocked) {
    // Remove background.
    backgroundPane.background = 'dockedBackground.png';
    
    // Set appropriate height.
    view.height = DOCKED_HEIGHT;
		labelSMS.visible = false;
		labelSMSText.visible = false;
		labelUnbilled.y = 75;
		labelAmountUnbilled.y = 75;
		divUserInfo.height = 61;
    // Hide the status area.
  //  statusArea.visible = false;    
  } else {
    // Show the background image.
    backgroundPane.background = 'background.png';

    // Set appropriate height.
    view.height = UNDOCKED_HEIGHT;
		labelSMS.visible = true;
		labelSMSText.visible = true;
		labelUnbilled.y = 101;
		labelAmountUnbilled.y = 101;
		divUserInfo.height = 97;
  }
}
function aLoginDetails_onclick() {
	  pluginHelper.showOptionsDialog();
}